package com.jinbai.repo;

import com.jinbai.data_object.AlbumDO;
import com.jinbai.util.DBUtil;
import com.jinbai.util.Log;
import com.jinbai.view_object.UserVO;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;

public class AlbumRepo {
    @SneakyThrows
    public AlbumDO selectAlbumByUidAndAid(int uid, int aid) {
        try (Connection con = DBUtil.connection()) {
            String sql = "select * from albums where uid = ? and aid = ?";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                ps.setInt(1, uid);
                ps.setInt(2, aid);
                try (final ResultSet rs = ps.executeQuery()) {
                    if (rs.next()) {
                        return new AlbumDO(rs.getInt("aid"), rs.getString("title"), rs.getString("cover"));
                    }
                }
            }
        }
        return null;
    }

    @SneakyThrows
    public void insertAlbum(UserVO userVO, String title, String coverUrl, int state) {
        try (Connection con = DBUtil.connection()) {
            String sql = "insert into albums (uid, title, cover, state) values (?, ?, ?, ?)";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                ps.setInt(1, userVO.getUid());
                ps.setString(2, title);
                ps.setString(3, coverUrl);
                ps.setInt(4, state);
                ps.executeUpdate();
                Log.println("创建专辑成功");
            }
        }
    }

    @SneakyThrows
    public List<AlbumDO> selectAlbumsByUid(int uid) {
        List<AlbumDO> ans = new LinkedList<>();
        try (Connection con = DBUtil.connection()) {
            String sql = "select * from albums where uid = ?";
            try (PreparedStatement ps = con.prepareStatement(sql)) {
                ps.setInt(1, uid);
                try (final ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        AlbumDO albumDO = new AlbumDO(rs.getInt("aid"),
                                rs.getString("title"),
                                rs.getString("cover"),
                                rs.getInt("state"));
                        Log.println("属于特定用户的专辑：" + albumDO);
                        ans.add(albumDO);
                    }
                }
            }
        }
        return ans;
    }
}
